package com.order.controller;

import com.order.common.PageQuery;
import com.order.common.Result;
import com.order.entity.SettlementRecord;
import com.order.service.SettlementService;
import com.order.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 结算控制器
 */
@RestController
@RequestMapping("/settlement")
@CrossOrigin
public class SettlementController {

    @Autowired
    private SettlementService settlementService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取结算记录列表
     */
    @GetMapping("/list")
    public Result<List<SettlementRecord>> getSettlementList(
            @RequestParam(required = false) Integer status,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有技术员可以查看自己的结算记录
            if (roleType != 4) {
                return Result.forbidden("只有技术员可以查看结算记录");
            }
            
            List<SettlementRecord> records = settlementService.getSettlementList(userId, status);
            return Result.success(records);
        } catch (Exception e) {
            return Result.error("获取结算记录失败");
        }
    }

    /**
     * 结算订单
     */
    @PostMapping("/{id}/settle")
    public Result<String> settleOrder(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 去掉Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Integer roleType = jwtUtil.getRoleTypeFromToken(token);
            
            // 只有管理员可以进行结算操作
            if (roleType != 1) {
                return Result.forbidden("只有管理员可以进行结算操作");
            }
            
            settlementService.settleOrder(id);
            return Result.success("结算成功");
        } catch (Exception e) {
            return Result.error("结算失败");
        }
    }
}